package zhengyanze.com.aipoemmax.guide.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zhengyanze.com.aipoemmax.R;
import zhengyanze.com.aipoemmax.guide.Constant;
import zhengyanze.com.aipoemmax.guide.adapter.MainAdapter;
import zhengyanze.com.aipoemmax.guide.bean.PoemBean;

public class SearchActivity extends AppCompatActivity {
    private static final String TAG = "SearchActivity";
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.rv_search)
    RecyclerView rvSearch;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.filed)
    ImageView filed;

    ArrayList<PoemBean> mPoemBean;
    private MainAdapter mainAdapter;

    String moreUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        mPoemBean = new ArrayList<>();

        initView();
    }

    /**
     * 初始化布局
     */
    public void initView() {
        rvSearch.setLayoutManager(new LinearLayoutManager(this));
        mainAdapter = new MainAdapter(mPoemBean);
        rvSearch.setAdapter(mainAdapter);

        //加载更多
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(2000);
                if (moreUrl != null) {
                    String url = Constant.URL.GUSHI_MORE + moreUrl;
                    initData(url, false);
                }
            }
        });
    }

    @OnClick(R.id.tv_search)
    public void onViewClicked() {
        String content = etKey.getText().toString();
        if (content == null || "".equals(content)) {
            Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = Constant.URL.GUSHI_SEARCH + content;
        initData(url, true);
    }


    /**
     * 加载网络
     */
    public void initData(final String url, final boolean isResh) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document document = Jsoup.connect(url).get();
                    Element main3 = document.getElementsByClass("main3").first();
                    Element left = main3.getElementsByClass("left").first();

                    Elements sons = left.getElementsByClass("sons");
                    if (sons == null || sons.isEmpty()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SearchActivity.this, "没有要查询的结果", Toast.LENGTH_SHORT).show();
                                filed.setVisibility(View.VISIBLE);
                            }
                        });
                        return;
                    }

                    final ArrayList<PoemBean> tempArray = new ArrayList<PoemBean>();
                    for (Element e : sons) {
                        Element cont = e.getElementsByClass("cont").first();

                        Element p = cont.getElementsByTag("p").first();
                        Element a = p.getElementsByTag("a").first();
//                        Log.e(TAG, "标题是 " + a.text());
                        String title = a.text();
//                        Log.e(TAG, "标题超链接是 " + Constant.URL.GUSHI_BASE + a.attr("href").toString());
                        String link = Constant.URL.GUSHI_BASE + a.attr("href").toString();

                        Element source = cont.getElementsByClass("source").first();
//                        Log.e(TAG, "作者是: " + source.text());
                        String author = source.text();

                        Element contson = e.getElementsByClass("contson").first();
//                        Log.e(TAG, "内容是: " + contson.text());
                        String content = contson.text();

                        PoemBean poemBean = new PoemBean(title, author, content, link);
                        tempArray.add(poemBean);
                    }

                    //获取超链接
                    Element pages = left.getElementsByClass("pages").last();
                    Element lastA = pages.getElementsByTag("a").last();
                    if (lastA == null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SearchActivity.this, "没有更多结果了", Toast.LENGTH_SHORT).show();
                            }
                        });
                        moreUrl = null;
                    }else{
//                        Log.e(TAG, "run: " + lastA.attr("href").toString());
                        moreUrl = lastA.attr("href").toString();
//                        Log.e(TAG, "run: " + moreUrl);
                    }

                    if (isResh) {
                        mPoemBean.clear();
                    }
                    mPoemBean.addAll(tempArray);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mPoemBean == null || mPoemBean.isEmpty()) {
                                filed.setVisibility(View.VISIBLE);
                            }else{
                                filed.setVisibility(View.GONE);
                            }
                            mainAdapter.notifyDataSetChanged();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
